package com.star.file.service.impl;

import com.alibaba.nacos.common.utils.IoUtils;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.star.common.core.utils.file.FileTypeUtils;
import com.star.file.config.FastDfsProperties;
import com.star.file.service.ISysFileService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * FastDFS 文件存储
 *
 * @author zhouhengzhe #公众号：小白的Java进阶之路
 */
@Service
@RequiredArgsConstructor
public class FastDfsSysFileServiceImpl implements ISysFileService {

    private final FastDfsProperties fastDfsProperties;

    private final FastFileStorageClient storageClient;

    /**
     * FastDfs文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        StorePath storePath = storageClient.uploadFile(inputStream, file.getSize(),
                FileTypeUtils.getExtension(file), null);
        IoUtils.closeQuietly(inputStream);
        return fastDfsProperties.getDomain() + "/" + storePath.getFullPath();
    }
}
